package com.hjh.thread.exchanger;

import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;

public class ExchangerDemo1 {



    public static void main(String[] args) {
        Exchanger<Object> exchanger = new Exchanger<>();
        Runnable1 runnable1= new Runnable1(exchanger,"name1","toValue1");
        Runnable1 runnable2= new Runnable1(exchanger,"name2","toValue2");
        new Thread(runnable1).start();
        new Thread(runnable2).start();
    }
}

class Runnable1 implements  Runnable{
    private Exchanger<Object> exchanger;
    private String name;
    private String toValue;

    public Runnable1(Exchanger<Object> exchanger,String name,String toValue){
        this.exchanger = exchanger;
        this.name = name;
        this.toValue = toValue;
    }

    @Override
    public void run() {
        try {
            TimeUnit.SECONDS.sleep( 5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        try {
            Object object = exchanger.exchange(toValue);
            System.out.println("=============>>"+name+"|toValue:"+toValue+ "|"+  object);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
